
const METHOD = {
    GET: 'GET',
    POST: 'POST',
    PUT: 'PUT',
    DELETE: 'DELETE'
}

class Request {

    interceptors = []

    intercept(res) {
        return this.interceptors
            .filter(f => typeof f === 'function')
            .every(f => f(res))
    }

    interceptor(f) {
        if (typeof f === 'function') {
            this.interceptors.push(f)
        }
        return this
    }
    _header = {
        'content-type': 'application/x-www-form-urlencoded'
    }


    request({ url, method, data, header = {} }) {
        return new Promise((resolve, reject) => {
            wx.request({
                url: url,
                method: method || METHOD.GET,
                data: {
                    ...data
                },
                header: {
                    ...this._header,
                    ...header
                },
                success: res => {
                    if (res.statusCode === 200) {
                        return this.intercept(res) && resolve(res)
                    }
                    return reject({
                        statusCode: res.statusCode
                    })
                },
                fail: reject
            });
        });
    }

    upload(url, filePath, name, formData, header = { 'content-type': 'multipart/form-data' }) {
        return new Promise((resolve, reject) => {
            wx.uploadFile({
                url: url,
                filePath: filePath,
                name: name,
                header: {
                    ...header
                },
                formData: {
                    ...formData
                },
                success: res => resolve(res),
                fail: reject
            });
        });
    }


    get(url, data, header) {
        return this.request({ url, method: METHOD.GET, data, header });
    }
    post(url, data, header) {
        return this.request({ url, method: METHOD.POST, data, header });
    }
    put(url, data, header) {
        return this.request({ url, method: METHOD.PUT, data, header });
    }
    delete(url, data, header) {
        return this.request({ url, method: METHOD.DELETE, data, header });
    }
}

export default new Request;
export {
    METHOD
}